# -*-encoding: Utf-8 -*-
# @File : extract_engine.py
# author: HJT
# Time：2024/3/31

import os
import yaml

from config.settings import ROOT_PATH
from .basic_extract import BasicExtract
from utils.log.logger import logger

# 全局变量池（yaml文件）
GLOBAL_FILE_NAME = os.path.join(ROOT_PATH, 'extract.yaml')


def extract_variables(case_data, response_data, f_name=GLOBAL_FILE_NAME):
    """
    处理各种extract提取
    :param case_data: yaml用例数据
    :param response_data: 响应数据
    :param f_name: 全局变量池（yaml文件）
    :return: None
    """
    # 提取至全局变量池
    GlobalExtract(case_data, response_data, f_name).main()
    # 提取至局部变量池
    return LocalExtract(case_data, response_data).main()


class GlobalExtract(BasicExtract):
    """
    变量，提取至全局：
      1、全局变量池
    """
    EX_TO_GLOBAL = 'extract'

    def __init__(self, case_data, response_data, f_name):
        super().__init__(case_data, response_data)
        self.extract_file_obj = open(f_name, mode='a', encoding='utf8')

    def _save_variable(self, name: str, val: str, extract_type):
        var_item = {name: val}
        yaml.dump(var_item, stream=self.extract_file_obj, allow_unicode=True)

    def main(self):
        if self.extract_to_file is None:
            return
        for var_name, var_val in self.extract_to_file.items():
            real_val = self._parse_variable(var_val)
            logger.info('提取Global变量：{' + f'{var_name}:{real_val}' + '}')
            self._save_variable(var_name, real_val, self.EX_TO_GLOBAL)

    def __del__(self):
        self.extract_file_obj.close()


class LocalExtract(BasicExtract):
    """
    变量，提取至局部：
      1、当前test.py模块
      2、当前的test类
    """
    EX_TO_CLASS = 'extract_to_class'
    EX_TO_MODULE = 'extract_to_module'

    def __init__(self, case_data, response_data):
        super().__init__(case_data, response_data)
        # TODO 怎么拿到当前的test类和test模块
        self.variable_dict = dict(class_={}, module_={})

    def _save_variable(self, name: str, val: str, extract_type):
        if extract_type == self.EX_TO_CLASS:
            # 保存到当前test类中
            self.variable_dict['class_'][name] = val
        elif extract_type == self.EX_TO_MODULE:
            # 保存到当前test模块中
            self.variable_dict['module_'][name] = val

    def main(self):
        if self.extract_to_class is not None:
            for var_name, var_val in self.extract_to_class.items():
                real_val = self._parse_variable(var_val)
                logger.info('提取Local-class变量：{' + f'{var_name}:{real_val}' + '}')
                self._save_variable(var_name, real_val, self.EX_TO_CLASS)

        if self.extract_to_module is not None:
            for var_name, var_val in self.extract_to_module.items():
                real_val = self._parse_variable(var_val)
                logger.info('提取Local-module变量：{' + f'{var_name}:{real_val}' + '}')
                self._save_variable(var_name, real_val, self.EX_TO_MODULE)

        return self.variable_dict
